package Finance::NSCC::Insurance::File;

use Moose;
use IO::File;
use DateTime;
use MooseX::Types::Path::Class qw/File/;
use Finance::NSCC::Insurance::Utils qw/trim/;

our $VERSION = '0.00100';

has filename        => (is => 'ro', isa => File, required => 1, coerce => 1);
has record_callback => (is => 'ro', isa => 'CodeRef', predicate => 'has_record_callback');

has records       => (is => 'ro', isa => 'ArrayRef', lazy_build => 1);
has _file_handle  => (is => 'ro', isa => 'IO::File', lazy_build => 1);

has nscc_num => (is => 'rw', isa => 'Str');
has file_date => (is => 'rw', isa => 'Str'); # isa => 'DateTime', coerce => 1
has record_count => (is => 'rw', isa => 'Int');
has test_indicator => (isa => 'Bool', reader => 'is_test', writer => '_test_indicator');
has carrier_company_id => (is => 'rw', isa => 'Str');

sub _build__file_handle {
  my $self = shift;
  my $file = $self->filename;
  $self->_error("file is not readable by effective uid/gid") unless -r $file;
  my $io = IO::File->new("<${file}") or $self->_error("Failed to open file");
  $io->getline;
  return $io;
}

sub BUILD{
  my $self = shift;
  $self->_process_header;
}

sub _process_header {
  my $self = shift;
  my $io = $self->_file_handle;
  my $line;
  my $head_re = ${ $self->blessed .'::RHEADER' }; #XXX
  if ( defined($line = $io->getline) && ( $line =~ /$head_re/) ) {
    $self->nscc_num( trim($1) );
    $self->file_date( trim($2) );
    $self->record_count( $3+0 );
    $self->_test_indicator( $4 eq 'T' ? 1 : 0 );
    $self->carrier_company_id( trim $5 );
    #$file_date =~ s/(....)(..)(..)/$1-$2-$3/;
  } else {
    $self->_error("Premature end on header record");
  }
}


sub _build_records {
  confess("unimplemented");
}

sub _error {
  my ($self, $error) = @_;
  my $message = "File '". $self->filename ."'";
  if($self->_has_file_handle ){
    $message .= " (".$self->_file_handle->input_line_number.")";
  }
  $message = "${message}: ${error}";
  die($message);
}

1;
